/*
 * Serum
 *
 * @license      GNU Lesser General Public Licence see LICENCE-LGPL file or http://www.gnu.org/licenses/lgpl.html
 */

Ext.namespace('Serum.Grid.Module.Core', 'Serum.Form.Module.Core');

Serum.Module.Core = Ext.extend(Serum.Module.Base, {
    listClass: function() {
        return 'Serum.Grid.Module.Core.Dashboard';
    },

    formClass: function() {
        return null;
    }
});

Serum.Grid.Module.Core.Dashboard = Ext.extend(Ext.ux.Portal, {

    /**
     * Constructor
     *
     * @param       {Object}    viewer
     */
    constructor: function(viewer) {
        this.viewer     = viewer;

        Serum.Grid.Module.Core.Dashboard.superclass.constructor.call(this, {
            tbar:       this.getToolbarButtons(),
            margins:    '35 5 5 0',
            border:     false,
            items:      []
        });

        this.loadSerumEvents();
        Serum.App.get().eventListener.fireEvent('widgets_modified');
    },

    /**
     * Returns the list of buttons of the toolbar
     *
     * @return  {Array}
     */
    getToolbarButtons: function() {
        var toolbar = [];

        toolbar.push('->');
        toolbar.push({
            tooltip:    {title: __('widgets~list_action_newwidget_title'),text: __('widgets~list_action_newwidget_description')},
            iconCls:    'img-add',
            handler:    this.onNewWidget,
            scope:      this
        });

        return toolbar;
    },

    onNewWidget: function() {
        var onSuccess = function() {
            Serum.App.get().eventListener.fireEvent('widgets_modified');
            win.close();
        }

        var form = new Serum.Form.Module.Core.AddWidget(onSuccess);
        form.preload();
        form.load();

        var win = new Ext.Window({
            layout:     'fit',
            title:      __('widgets~list_action_newwidget_title'),
            width:      420,
            height:     200,
            closable:   true,
            resizable:  false,
            plain:      true,
            border:     false,
            autoScroll: true,

            items:      [form]
        });

        win.show();
    },
    
    /**
     * Returns panel title
     *
     * @return  {String}
     */
    getTitle: function() {
        return 'Serum';
    },

    /**
     * Loads Serum global events
     */
    loadSerumEvents: function() {
        Serum.App.get().eventListener.on('widgets_modified',     this.onRefreshDashboard,     this);
    },

    /**
     * Unloads Serum global events
     */
    unloadSerumEvents: function() {
        Serum.App.get().eventListener.un('widgets_modified',     this.onRefreshDashboard,     this);
    },

    onActionChanged: function() {

    },

    /**
     * Event handler
     */
    onDeleteWidget: function(widget) {
        Ext.Msg.show({
           title:   __('widgets~delete_question'),
           buttons: Ext.Msg.YESNO,
           fn:      function(btn) {
                        if (btn != 'yes') {
                            return;
                        }

                        Serum.Ajax.request({
                            scope:       this,
                            params:      {
                                            method:         Serum.Selector.get().method({
                                                                                            module:         'Widgets',
                                                                                            controller:     'Index',
                                                                                            action:         'delete'
                                                                                        }),
                                            widget:         widget['id'],
                                            requestId:      Serum.Helper.Request.id()
                                        },

                            onSuccess:  function(response) {
                                            Serum.App.get().eventListener.fireEvent('widgets_modified');
                                       }
                        });
           }
        });
    },

    /**
     * Event handler
     */
    onEditWidget: function(widget) {
        var onSuccess = function() {
            Serum.App.get().eventListener.fireEvent('widgets_modified');
            win.close();
        }

        var form = new Serum.Form.Module.Core.EditWidget(onSuccess);
        form.preload(widget['id']);
        form.load();

        var win = new Ext.Window({
            layout:     'fit',
            title:      __('widgets~window_edit_title'),
            width:      420,
            height:     250,
            closable:   true,
            resizable:  false,
            plain:      true,
            border:     false,
            autoScroll: true,

            items:      [form]
        });

        win.show();
    },

    /**
     * Refresh dashboard widgets
     */
    onRefreshDashboard: function() {
        Serum.Ajax.request({
            scope:       this,
            params:      {
                            method:         Serum.Selector.get().method({
                                                                            module:         'Widgets',
                                                                            controller:     'Index',
                                                                            action:         'getList'
                                                                        }),
                            requestId:      Serum.Helper.Request.id()
                        },

            onSuccess:  function(response) {
                            var jsonResponse    = Ext.util.JSON.decode(response.responseText);
                            var result          = jsonResponse.result;
                            var items           = [];

                            for (var r = 0; r < result.length; r++) {
                                var widget = result[r];

                                var className = widget['class_name'].split('_');

                                if (typeof Serum.Widgets.Module[className[0]][className[3]] === 'function') {
                                    var oWidget = new Serum.Widgets.Module[className[0]][className[3]]();

                                    var item = oWidget.getItem(widget['params']);

                                    // Dependency injection
                                    item.style  = item.style    || 'padding: 0 0 10px 0';
                                    item.frame  = item.frame    || false;
                                    item.border = item.border   || true;
                                    item.title  = item.title    || widget['name'];

                                    item.tools = [{
                                                    id:         'gear',
                                                    handler:    function() {
                                                        this.onEditWidget(widget);
                                                    },
                                                    scope:      this
                                                  },
                                                  {
                                                    id:         'close',
                                                    handler:    function(e, target, panel){
                                                        this.onDeleteWidget(widget);
                                                    },
                                                    scope:      this
                                                  }];

                                    items.push(item);
                                }
                            }

                            if (typeof this.items !== 'undefined') {
                                var flex;
                                while (flex = this.items.last()) {
                                    this.remove(flex, true);
                                }
                            }

                            var column0 = [];
                            var column1 = [];

                            for (var i = 0; i < items.length; i++) {
                                if (i % 2 == 0) {
                                    column0.push(items[i]);
                                } else {
                                    column1.push(items[i]);
                                }
                            }

                            if (column0.length > 0) {
                                this.add(
                                    {
                                        columnWidth:    .5,
                                        style:          'padding:10px 0 10px 10px',
                                        items:          column0
                                    });
                            }

                            if (column1.length > 0) {
                                this.add(
                                    {
                                        columnWidth:    .5,
                                        style:          'padding:10px 10px 10px 10px',
                                        items:          column1
                                    });
                            }

                            this.doLayout();
                       }
        });
    }
});

Serum.Form.Module.Core.AddWidget = Ext.extend(Serum.Form.Module.Edit, {

    /**
     * Constructor
     */
    constructor: function(onSuccess) {
        Serum.Form.Module.Core.AddWidget.superclass.constructor.call(this, {}, {
            module:         'Widgets',
            controller:     'Index',
            action:         'add',
            saveAction:     'saveAdd'
        }, onSuccess);
    },

    fieldsList: function(results) {
        if (results['default'].widget.values.length > 0) {
            return {
                'add': [
                    {
                        'widget':         {}
                    }
                ]
            };
        } else {
            return {
                'empty': [
                    {
                        'widget':         {
                            xtype: 'label',
                            text:  __('widgets~empty')
                        }
                    }
                ]
            };
        }
    }

});

Serum.Form.Module.Core.EditWidget = Ext.extend(Serum.Form.Module.Edit, {

    /**
     * Constructor
     */
    constructor: function(onSuccess) {
        Serum.Form.Module.Core.EditWidget.superclass.constructor.call(this, {}, {
            module:         'Widgets',
            controller:     'Index',
            action:         'edit',
            saveAction:     'saveEdit'
        }, onSuccess);
    }
});